package com.white.aspect;

import com.white.bean.Article;
import com.white.bean.UserModel;
import com.white.service.ArticleService;
import com.white.service.UserModelService;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 增加浏览数量切面
 */
@Aspect
@Component
public class ViewIncAspect {

    @Autowired
    ArticleService articleService;

    @Autowired
    UserModelService userModelService;

    /**
     * 配置切点
     */
    @Pointcut("@annotation(com.white.annotation.ViewInc)")
    public void pointcut() {}

    /**
     * 前置通知
     */
    @Before("pointcut()")
    public void before() {
    }

    /**
     * 后置通知
     */
    @After("pointcut()")
    public void after() {
    }

    /**
     * 返回通知
     */
    @AfterReturning(returning = "ans", pointcut = "pointcut()")
    public void afterReturning(Map<String, Object> ans) {
        Long articleId = (Long) ans.get("articleId");
        Long userId = (Long) ans.get("userId");
        /*增加文章的浏览次数*/
        articleService.viewsInc(articleId);
        Article article = articleService.getById(articleId);
        /*检查用户模型是否存在*/
        if (userModelService.getUserModel(userId, article.getClassifyId()) == null) {
            userModelService.myCreate(new UserModel(userId, article.getClassifyId()));
        }
        /*增加用户模型的浏览次数*/
        userModelService.viewsInc(userId, article.getClassifyId());
    }

}
